import { timeline, logger } from '@/instance'
import { onMounted, onUnmounted, Ref, ref } from 'vue'
export type PlayerComposition = {
  width: number
  height: number
  canvas: Ref<HTMLCanvasElement | null>
}

export function usePlayer(): PlayerComposition {
  let context: CanvasRenderingContext2D | null = null
  const canvas: Ref<HTMLCanvasElement | null> = ref(null)
  let rafId = -1
  onMounted(() => {
    context = canvas.value!.getContext('2d')
    logger.log('composables/player', 'getContext', context)
    const draw = () => {
      timeline.tracks.forEach((track) => {
        track.view && context!.drawImage(track.view, 0, 0, 640, 360)
      })
      rafId = requestAnimationFrame(draw)
    }
    draw()
  })
  onUnmounted(() => {
    cancelAnimationFrame(rafId)
  })
  return {
    width: 640,
    height: 360,
    canvas,
  }
}
